package com.xxxx;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.checkpoint.ListCheckpointed;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Collections;
import java.util.List;

public class Hello01FlinkOperatorState {
    public static void main(String[] args) throws Exception {

        //创建环境
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //获取数据源
        DataStreamSource<String> source = environment.socketTextStream("192.168.88.101", 18880);
        //转换操作
        source.map(new OperatorStateMapFunction()).setParallelism(2).print().setParallelism(2);

        //开启环境
        environment.execute("Hello01FlinkOperatorState" + System.currentTimeMillis());
    }
}

class OperatorStateMapFunction implements MapFunction<String, String>, ListCheckpointed<Integer> {

    private int count;

    @Override
    public String map(String word) throws Exception {
        return word + "--" + ++count;
    }

    @Override
    public List<Integer> snapshotState(long checkpointId, long timestamp) throws Exception {
        System.out.println("OperatorStateMapFunction.snapshotState[" + checkpointId + "][" + timestamp + "]");
        return Collections.singletonList(count);
    }

    @Override
    public void restoreState(List<Integer> list) throws Exception {
        if (list == null || list.size() == 0) {
            count = 0;
        } else {
            count = list.get(list.size() - 1);
        }
    }
}
